//
//  SumitViewController.m
//  HengHuaSupervision
//
//  Created by XD-XY on 3/22/14.
//  Copyright (c) 2014 XD-XY. All rights reserved.
//  提交页面

#import "SumitViewController.h"
#import "XDHeader.h"
#import "XDTools.h"
#import "SupervisionSumitCell.h"
#import "MyFile.h"
#import "Request.h"
#import "Response.h"
#import "ZipArchive.h"

#define tableviewwidth 1004

@interface SumitViewController ()

@end

@implementation SumitViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];

}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    self.sumitDataArray = [[NSMutableArray alloc] init];
    self.failSumitArray = [[NSMutableArray alloc] init];
    
    self.titleLabel.text = @"未提交标签";
    self.initlalizeBtn.hidden =YES;
    self.initlalizeLabel.hidden =YES;
    self.waitSubmitLabel.text = @"一键提交";
    
    [self initSumitTableViewHeader]; //初始化表头
    [self initSumitTableView];      //创建列表

    [self initSumitDatas];
}

#pragma mark ==================UI create ======================
-(void)initSumitTableViewHeader
{
    //创建表头
    headerTableView  = [[UITableView alloc] initWithFrame:CGRectMake(10,20, tableviewwidth,mHomepage_head_Height) style:UITableViewStylePlain];
    headerTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    headerTableView.delegate = self;
    headerTableView.dataSource = self;
    headerTableView.userInteractionEnabled=NO;
    headerTableView.backgroundColor = [UIColor clearColor];
    [self.contentView addSubview:headerTableView];
}

-(void)initSumitTableView
{
    //创建列表
    self.sumitTableView = [[UITableView alloc] initWithFrame:CGRectMake(10, height_y(headerTableView), tableviewwidth, self.contentView.frame.size.height-(height_y(headerTableView))) style:UITableViewStylePlain];
    _sumitTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _sumitTableView.delegate = self;
    _sumitTableView.dataSource = self;
    _sumitTableView.backgroundColor = [UIColor clearColor];
    [self.contentView addSubview:_sumitTableView];
}

#pragma mark =====================赋值===============================
-(void)initSumitDatas
{
    [_sumitDataArray removeAllObjects];
    FMDatabase * db = [XDTools getDb];
    if (![db open]){
        DDLOG(@"取未提交数据-->打开数据库失败");
        return;
    }
    FMResultSet * rs = [db executeQuery:@"SELECT * FROM T_TRACE_SUMIT"];
    while ([rs next]) {
        self.pressItem = [[PressItem alloc] init];
        _pressItem.photphotos = [[NSMutableArray alloc] init];
        _pressItem.breviaryphotos = [[NSMutableArray alloc] init];
        _pressItem.assert_id = [rs objectForColumnName:@"assert_id"];
        _pressItem.propertyWithlabel_record_id = [rs objectForColumnName:@"propertyWithlabel_record_id"];
        _pressItem.tag_code = [rs objectForColumnName:@"tag_code"];
        _pressItem.part = [rs objectForColumnName:@"part"];
        _pressItem.create_time = [rs objectForColumnName:@"create_time"];
        _pressItem.supervision_record_id = [rs objectForColumnName:@"supervision_record_id"];
        _pressItem.notes = [rs objectForColumnName:@"notes"];
        _pressItem.scan_record_id = [rs objectForColumnName:@"scan_record_id"];
        _pressItem.scan_time = [rs objectForColumnName:@"scan_time"];
        _pressItem.scan_location = [rs objectForColumnName:@"scan_location"];
        _pressItem.scan_location_gps = [rs objectForColumnName:@"scan_location_gps"];
        _pressItem.scan_device = [rs objectForColumnName:@"scan_device"];
        _pressItem.scan_devicename = [rs objectForColumnName:@"scan_devicename"];
        _pressItem.scan_userid = [rs objectForColumnName:@"scan_userid"];
        _pressItem.scan_username = [rs objectForColumnName:@"scan_username"];
        _pressItem.scan_status = [rs objectForColumnName:@"scan_status"];
        _pressItem.name = [rs objectForColumnName:@"name"];
        _pressItem.assert_code = [rs objectForColumnName:@"assert_code"];
        NSString * breviaryphotoString = [rs objectForColumnName:@"breviaryphotos"];
        NSString * photphotoStirng = [rs objectForColumnName:@"photphotos"];
        if (IS_NOT_EMPTY(breviaryphotoString)){
            [_pressItem.breviaryphotos addObjectsFromArray:[breviaryphotoString componentsSeparatedByString:@","]];
        }
        if (IS_NOT_EMPTY(photphotoStirng)){
            [_pressItem.photphotos addObjectsFromArray:[photphotoStirng componentsSeparatedByString:@","]];
        }
        
        [_sumitDataArray addObject:_pressItem];
    }
    [db close];
    
    
    if ([_sumitDataArray count]==0){
        self.waitSubmitBtn.hidden =YES;
        self.waitSubmitLabel.hidden =YES;
        self.remindBtn.hidden =YES;
    }else{
        self.waitSubmitBtn.hidden = NO;
        self.waitSubmitLabel.hidden =NO;
        self.remindBtn.hidden =NO;
        
        //排序
        NSArray * tArr = [NSArray arrayWithArray:_sumitDataArray];
        [_sumitDataArray removeAllObjects];
        for(int k =[tArr count]-1;k >= 0;k--){
            [_sumitDataArray addObject:[tArr objectAtIndex:k]];
        }
        
        self.titleLabel.text = [NSString stringWithFormat:@"未提交标签(%d)",[_sumitDataArray count]];
    }
    
    [_sumitTableView reloadData];
    
    if([_sumitDataArray count]==0){
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"waitCunitCount"];
    }else{
        [[NSUserDefaults standardUserDefaults] setValue:[NSString stringWithFormat:@"%d",[_sumitDataArray count]] forKey:@"waitCunitCount"];
    }
    [[NSUserDefaults standardUserDefaults] synchronize];
}


#pragma mark =====================UITbaleview delegate===============
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(tableView == headerTableView){
        return 1;
    }else{
        return [_sumitDataArray count];
    }
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == headerTableView){
        return mHomepage_head_Height;
    }
    return mHomepage_Cell_Height;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView == headerTableView){
        static NSString * cellName = @"cell";
        SupervisionSumitCell * cell =[tableView  dequeueReusableCellWithIdentifier:cellName];
        if (cell == nil){
            cell = [[SupervisionSumitCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellName];
        }
        cell.diselectBg.image = [XDTools stretchableImag:mHomepage_Head_bg_Img];
        [cell isHarderTableViewCell];
        
        cell.assertidLabel.text = [self.sumit_info_array objectAtIndex:0];
        cell.assertnameLabel.text = [self.sumit_info_array objectAtIndex:1];
        cell.tagidLabel.text = [self.sumit_info_array objectAtIndex:2];
        cell.partLabel.text = [self.sumit_info_array objectAtIndex:3];
        cell.locationLabel.text = [self.sumit_info_array objectAtIndex:4];
        cell.creatTimeLabel.text = [self.sumit_info_array objectAtIndex:5];
        
        return cell;
        
    }else{
        static NSString * cellName = @"cell";
        SupervisionSumitCell * cell =[tableView  dequeueReusableCellWithIdentifier:cellName];
        if (cell == nil){
            cell = [[SupervisionSumitCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellName];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        if (indexPath.row%2){
            cell.diselectBg.image = [XDTools stretchableImag:mHomepage_Cell_Even_Img];
        }else{
            cell.diselectBg.image = [XDTools stretchableImag:mHomepage_Cell_Odd_Img];
        }
        if ([_sumitDataArray count]==0){
            return cell;
        }
        PressItem * item = [_sumitDataArray objectAtIndex:indexPath.row];
        cell.assertidLabel.text = item.assert_code;
        cell.assertnameLabel.text = item.name;
        cell.tagidLabel.text = item.tag_code;
        cell.partLabel.text = item.part;
        if (IS_NOT_EMPTY(item.scan_location)){
            cell.locationLabel.text = item.scan_location;
        }else{
            cell.locationLabel.text = item.scan_location_gps;
        }
        cell.creatTimeLabel.text = [[XDTools sharedXDTools] intervalSinceNow:item.create_time];
        
        CGRect asRect = [XDTools xyAutoSizeOfWidget:cell.assertidLabel andSize:CGSizeMake(346/2.0f,mHomepage_Cell_Height) andtextFont:15];
        CGRect naRect = [XDTools xyAutoSizeOfWidget:cell.assertnameLabel andSize:CGSizeMake(188/2.0f,mHomepage_Cell_Height) andtextFont:15];
        CGRect tagRect = [XDTools xyAutoSizeOfWidget:cell.tagidLabel andSize:CGSizeMake(346/2.0f,mHomepage_Cell_Height) andtextFont:15];
        CGRect adRect = [XDTools xyAutoSizeOfWidget:cell.locationLabel andSize:CGSizeMake(518/2.0f,mHomepage_Cell_Height) andtextFont:15];
        
        cell.assertidLabel.frame = CGRectMake(asRect.origin.x, asRect.origin.y,346/2.0f, mHomepage_Cell_Height);
        cell.assertnameLabel.frame = CGRectMake(naRect.origin.x,naRect.origin.y,188/2.0f, mHomepage_Cell_Height);
        cell.tagidLabel.frame= CGRectMake(tagRect.origin.x, tagRect.origin.y, 346/2.0f, mHomepage_Cell_Height);
        cell.locationLabel.frame= CGRectMake(adRect.origin.x, adRect.origin.y,518/2.0f, mHomepage_Cell_Height);
        
        return cell;
    }
}

#pragma mark ==============重写XDBaseViewController中的方法=================
-(void)gotoSubmitViewController
{
    if (![XDTools NetworkReachable]){
        [XDTools showTips:@"未连接到网络" toView:[UIApplication sharedApplication].keyWindow];
        return;
    }
    
    [_failSumitArray removeAllObjects];
    hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    hud.labelText = [NSString stringWithFormat:@"提交个数:%d/%d",_count,[_sumitDataArray count]];
    _count =0;
    _number = 0;
    for (int i = 0 ;i <[_sumitDataArray count];i++){
        PressItem * item = [_sumitDataArray objectAtIndex:i];
        
        Request* req = [[Request alloc] init];
        //content_json串
        NSMutableDictionary * data = [self adjustmentContentJson:item];
        
        //此处因将多个文件压缩成一个zip文件
        NSString * string1 = IMG_FILESAVEPATH;
        NSString * fileString = [NSString stringWithFormat:@"%@photphotoFile.zip",item.supervision_record_id];
        NSString * fileString2 = [NSString stringWithFormat:@"%@breviaryphotoFile.zip",item.supervision_record_id];
        NSString *photphotoFile = [string1 stringByAppendingPathComponent:fileString];
        NSString * breviaryphotoFile = [string1 stringByAppendingPathComponent:fileString2];
        ZipArchive * zaPhotphoto = [[ZipArchive alloc] init];
        ZipArchive * zaBreviaryphoto = [[ZipArchive  alloc] init];
        [zaPhotphoto CreateZipFile2:photphotoFile];
        [zaBreviaryphoto CreateZipFile2:breviaryphotoFile];
        for (int i = 0 ; i < [item.photphotos count];i++){
            NSRange range = [[item.photphotos objectAtIndex:i] rangeOfString:@"law_"];
            NSString * string =[[item.photphotos objectAtIndex:i] substringFromIndex:range.location];
            [zaPhotphoto addFileToZip:[item.photphotos objectAtIndex:i] newname:string];
        }
        BOOL success = [zaPhotphoto CloseZipFile2];
        DDLOG(@"Zipped file with result %d",success);
        
        for (int i = 0 ;i <[item.breviaryphotos count];i++){
            NSRange range = [[item.breviaryphotos objectAtIndex:i] rangeOfString:@"thum_"];
            NSString * string =[[item.breviaryphotos objectAtIndex:i] substringFromIndex:range.location];
            [zaBreviaryphoto addFileToZip:[item.photphotos objectAtIndex:i] newname:string];
        }
        BOOL success2 = [zaBreviaryphoto CloseZipFile2];
        DDLOG(@"Zipped file with result %d",success2);
        
        MyFile * f1 = [[MyFile alloc] init];
        NSString * fileName1 = fileString2;
        f1.path = [string1 stringByAppendingPathComponent:fileName1];
        f1.name = fileName1;
        f1.length = [[XDTools sharedXDTools] fileSizeAtPath:f1.path];
        
        MyFile * f2 = [[MyFile alloc] init];
        NSString * fileName2 = fileString;
        f2.path = [string1 stringByAppendingPathComponent:fileName2];
        f2.name = fileName2;
        f2.length = [[XDTools sharedXDTools] fileSizeAtPath:f2.path];
        
        NSArray * fileArray = [[NSArray alloc] initWithObjects:f1,f2, nil];
        
        NSArray * postData = [[NSArray alloc] initWithObjects:data, nil];
        [req uploadFile:mTrace_Upsupervisiondatas keyValue:(NSDictionary *)postData file:fileArray progressObserver:self completionHandler:^(ResponseData *datas) {
            if ([datas.result intValue]==1){
                _count++;
                hud.labelText = [NSString stringWithFormat:@"提交个数:%d/%d",_count,[_sumitDataArray count]];
//                if (_count == [_sumitDataArray count]){
//                    hud.labelText =@"全部提交成功";
//                    [XDTools hideProgress:[UIApplication sharedApplication].keyWindow];
////                    self.remindBtn.hidden =YES;
//                }
//                [self.remindBtn setTitle:[NSString stringWithFormat:@"%d",[_sumitDataArray count]-_count] forState:UIControlStateNormal];
                
            }else{
                [_failSumitArray addObject:item];
//                [XDTools hideProgress:[UIApplication sharedApplication].keyWindow];
//                [XDTools showTips:datas.errorMsg toView:[UIApplication sharedApplication].keyWindow];
            }
            _number++;
            if (_number == [_sumitDataArray count]){
                [self clearSumitTable];
            }
        }];
    }
}

#pragma mark ==================调整成content_json 格式===================
-(NSMutableDictionary * )adjustmentContentJson:(PressItem * )item
{
    //设备标签关联表每条记录
    NSDictionary * asserttagDict =[self setAssertTagDict:item];
    //贴标签信息每条记录
    NSDictionary * supervisionDict = [self setSupervisionDict:item];
    //扫描信息每条记录
    NSMutableDictionary * scanDict = [self setScanDict:item];
    
    NSMutableArray * assertArray = [[NSMutableArray alloc] init];
    [assertArray addObject:asserttagDict];
    
    NSMutableArray * supervisionArray = [[NSMutableArray alloc] init];
    [supervisionArray addObject:supervisionDict];
    
    NSMutableArray * scanArray = [[NSMutableArray alloc] init];
    [scanArray addObject:scanDict];
    
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
    [dict setValue:assertArray forKey:@"asserttag"];
    [dict setValue:supervisionArray forKey:@"supervision"];
    [dict setValue:scanArray forKey:@"scan"];
    
    NSMutableDictionary * data = [[NSMutableDictionary alloc] init];
    [data setValue:item.assert_id forKey:@"assert_id"];
    [data setValue:dict forKey:@"data"];
    
    return data;
}

-(NSDictionary * )setAssertTagDict:(PressItem *)item
{   //设备标签关联表
    NSDictionary * data = [[NSDictionary alloc] initWithObjectsAndKeys:item.propertyWithlabel_record_id,@"id",item.tag_code,@"tag_code",item.part,@"part",item.create_time,@"create_time",nil];
    return data;
}

-(NSDictionary *)setSupervisionDict:(PressItem *)item
{
    //贴标签表（监造表）
    NSDictionary * data;
    if (IS_NOT_EMPTY(item.notes)){
        data = [[NSDictionary alloc] initWithObjectsAndKeys:item.supervision_record_id,@"id",item.notes,@"notes",nil];
    }else{
        data = [[NSDictionary alloc] initWithObjectsAndKeys:item.supervision_record_id,@"id", nil];
    }
    return data;
}

-(NSMutableDictionary *)setScanDict:(PressItem *)item
{
    //扫描记录表
    NSMutableArray * marray1 = [[NSMutableArray alloc] init];
    for (int i =0;i<[item.breviaryphotos count];i++){
        NSRange range = [[item.breviaryphotos objectAtIndex:i] rangeOfString:@"thum_"];
        NSString * string =[[item.breviaryphotos objectAtIndex:i] substringFromIndex:range.location];
        [marray1 addObject:string];
    }
    
    NSMutableArray * marray2 = [[NSMutableArray alloc] init];
    for (int i =0;i<[item.photphotos count];i++){
        NSRange range = [[item.photphotos objectAtIndex:i] rangeOfString:@"law_"];
        NSString * string =[[item.photphotos objectAtIndex:i] substringFromIndex:range.location];
        [marray2 addObject:string];
    }
    
    NSMutableDictionary * photosDict = [[NSMutableDictionary alloc] init];
    [photosDict setValue:marray1 forKey:@"breviaryphotos"];
    [photosDict setValue:marray2 forKey:@"photphotos"];
    
    NSMutableDictionary * data = [[NSMutableDictionary alloc] init];
    [data setValue:item.scan_record_id forKey:@"id"];
    [data setValue:item.tag_code forKey:@"tag_code"];
    [data setValue:item.scan_time forKey:@"scan_time"];
    [data setValue:item.scan_location_gps forKey:@"scan_location_gps"];
    [data setValue:item.scan_location forKey:@"scan_location"];
    [data setValue:item.scan_device forKey:@"scan_device"];
    [data setValue:item.scan_devicename forKey:@"scan_devicename"];
    [data setValue:item.scan_userid forKey:@"scan_userid"];
    [data setValue:item.scan_username forKey:@"scan_username"];
    [data setValue:item.scan_status forKey:@"scan_status"];
    [data setValue:photosDict forKey:@"photos"];
    
    return data;
}

#pragma mark ===================清除数据库中待提交表中的提交成功的记录====================
-(void)clearSumitTable
{

//    [XDTools sharedXDTools].waitCumitCount = [NSString stringWithFormat:@"%d",[_failSumitArray count]];
    
    if([_failSumitArray count]!=0){
        self.titleLabel.text = [NSString stringWithFormat:@"未提交标签(%d)",[_failSumitArray count]];
        [[NSUserDefaults standardUserDefaults] setValue:[NSString stringWithFormat:@"%d",[_failSumitArray count]] forKey:@"waitCunitCount"];
        [XDTools hideProgress:[UIApplication sharedApplication].keyWindow];
        [XDTools showTips:[NSString stringWithFormat:@"有%d条记录提交失败",[_failSumitArray count]] toView:[UIApplication sharedApplication].keyWindow];
        
        for (int i = 0 ; i<[_sumitDataArray count]; i++) {
            BOOL isDelete = YES;
            PressItem * item = [_sumitDataArray objectAtIndex:i];
            for (PressItem * iitem in _failSumitArray){
                if ([item.supervision_record_id isEqualToString:iitem.supervision_record_id]){
                    isDelete = NO;
                    break;
                }
            }
            if (isDelete){
                PressItem * iteme = [_failSumitArray objectAtIndex:i];
                FMDatabase * db = [XDTools getDb];
                if (![db open]){
                    DDLOG(@"一键提交-->部分提交成功-->清除表数据-->打开数据库失败");
                    return;
                }
                BOOL a = [db executeUpdate:@"DELETE FROM T_TRACE_SUMIT WHERE supervision_record_id = ?",iteme.supervision_record_id];
                if (!a){
                    DDLOG(@"一键提交-->部分提交成功-->清除表数据-->清除失败");
                }
                [db close];
            }
        }

    }else{
        [XDTools sharedXDTools].isupClick =YES;
        self.titleLabel.text = @"未提交标签";
        hud.labelText =@"全部提交成功";
        [XDTools hideProgress:[UIApplication sharedApplication].keyWindow];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"waitCunitCount"];
        FMDatabase * db = [XDTools getDb];
        if (![db open]){
            DDLOG(@"一键提交-->全部提交成功-->清除表数据-->打开数据库失败");
            return;
        }
        BOOL a = [db executeUpdate:@"DELETE FROM T_TRACE_SUMIT"];
        if (!a){
            DDLOG(@"一键提交-->全部提交成功-->清除表数据-->清除失败");
        }
        [db close];
    }
    
    [self initSumitDatas];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
